package com.example.smart.order.controller;

import com.example.smart.order.entity.Category;
import com.example.smart.order.entity.Dish;
import com.example.smart.order.mapper.CategoryMapper;
import com.example.smart.order.mapper.DishMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜品类别控制器，处理与菜品类别相关的HTTP请求
 */
@RestController
@Slf4j
@RequestMapping("/api/categories")
public class CategoryController {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private DishMapper dishMapper;

    /**
     * 增加类别
     *
     * @param category 菜品类别对象
     * @return 处理结果，1表示成功，-1表示失败
     */
    @PostMapping("/addNew")
    public int addNew(@RequestBody Category category) {
        log.debug("增加类别: {}", category);
        String categoryName = category.getName();
        int count = categoryMapper.countByName(categoryName);
        if (count > 0) {
            log.debug("类别名称已存在: {}", categoryName);
            return -1;
        }
        int result = categoryMapper.insert(category);
        log.debug("增加类别结果: {}", result);
        return result;
    }

    /**
     * 根据ID删除类别
     *
     * @param categoryId 菜品类别ID
     * @return 处理结果，1表示成功，-1表示失败
     */
    @PostMapping("/delete")
    public int delete(Long categoryId) {
        log.debug("删除类别, ID: {}", categoryId);
        List<Dish> dishes = dishMapper.selectByCategoryId(categoryId);
        if (dishes.size() > 0) {
            log.debug("存在菜品，删除操作被阻止");
            return -1;
        }
        int result = categoryMapper.deleteById(categoryId);
        log.debug("删除类别结果: {}", result);
        return result;
    }

    /**
     * 根据ID修改类别
     *
     * @param category 菜品类别对象
     * @return 处理结果，1表示成功，-1表示失败
     */
    @PostMapping("/update")
    public int update(@RequestBody Category category) {
        log.debug("修改类别: {}", category);
        String categoryName = category.getName();
        int count = categoryMapper.countByName(categoryName);
        if (count > 0) {
            log.debug("类别名称已存在: {}", categoryName);
            return -1;
        }
        int result = categoryMapper.updateById(category);
        log.debug("修改类别结果: {}", result);
        return result;
    }

    /**
     * 根据ID查询类别
     *
     * @param categoryId 菜品类别ID
     * @return 菜品类别对象
     */
    @RequestMapping("/query")
    public Category query(Long categoryId) {
        log.debug("查询类别, ID: {}", categoryId);
        Category category = categoryMapper.selectById(categoryId);
        log.debug("查询到类别: {}", category);
        return category;
    }

    /**
     * 获取菜品类别列表
     *
     * @return 菜品类别列表
     */
    @RequestMapping("")
    public List<Category> getCategories() {
        log.debug("获取菜品类别列表");
        List<Category> categories = categoryMapper.selectAll();
        log.debug("查询到菜品类别列表: {}", categories);
        return categories;
    }
}